package com.csot.service;

import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

import org.springframework.beans.BeanUtils;

import com.csot.model.CityIp;
import com.csot.model.CitySegment;
import com.jfinal.plugin.activerecord.Db;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.net.NetUtil;

public class CitySegmentDetail {

    static final Deque<CitySegment> queue = ListUtil.toLinkedList();

    public void run(String city) {
        // TODO Auto-generated method stub

        List<CitySegment> csList = new CitySegment()
                .dao()
                .find("select * from t_city_segment where id not IN (select ip_segment_id from t_city_ip) and ip_city = ?"
                        , city);
        if (CollUtil.isEmpty(csList)) {
            return;
        }

        queue.addAll(csList);

        while (!queue.isEmpty()) {
            CitySegment f = queue.poll();
            Db.tx(() -> {
                List<CityIp> ciList = new ArrayList<>();
                for (long i = f.getIpStartI(); i <= f.getIpEndI(); i++) {
                    CityIp ci = new CityIp();
                    BeanUtils.copyProperties(f, ci, "id");
                    ci.setIpAddressI(i);
                    ci.setIpAddress(NetUtil.longToIpv4(i));
                    ci.setIpSegmentId(f.getId());
                    ci.setIpStatus("off");
                    ci.setRecordStatus("on");
                    ci.setRecordType("zy");
                    ci.setAddressStatus("kx");
                    ciList.add(ci);
                }
                Db.batchSave(ciList, 999);
                return true;
            });
        }
    }

    public List<CitySegment> getSlot() {
        // TODO Auto-generated method stub

        CitySegment dao = new CitySegment().dao();
        List<CitySegment> csList = dao
                .find("select * from t_city_segment t where id not IN (select ip_segment_id from t_city_ip)");
        return csList;

    }

}
